package com.example.demo.io;

import com.example.demo.model.LoginInfo;

import java.io.*;

/**
 * @author luowj12
 * @since 2021/4/7 10:24
 */
public class FileStreamTest {

    public static void main(String[] args) {
        //write();
        read();
    }

    public static void write(){
        String fileName = "test.txt";  //文件名
        LoginInfo info = new LoginInfo("chen","123"); //某个待序列化对象，LoginInfo类须实现Serializable接口
        ObjectOutputStream oos = null; //创建输出流
        try {
            oos = new ObjectOutputStream(new FileOutputStream(fileName));
            oos.writeObject(info);   //序列化
            oos.close();   //关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void read(){
        String fileName = "test.txt";
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
            LoginInfo info2 = (LoginInfo)ois.readObject();
            System.out.println("用户名:"+info2.getPassword());
            System.out.println("密码:"+info2.getPassword());
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
